package cn.ddiancan.xddcloud.ddccore.mulidatasource.aspect;

import cn.ddiancan.xddcloud.ddccore.annotation.MultiDBS;
import cn.ddiancan.xddcloud.ddccore.mulidatasource.context.DataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 多数据源切面
 *
 * @author Amos
 * @since 2024-08-19
 */
@Aspect
@Component
public class MultiDataSourceAspect {

    private static final Logger logger = LoggerFactory.getLogger(MultiDataSourceAspect.class);

    @Pointcut("@annotation(cn.ddiancan.xddcloud.ddccore.annotation.MultiDBS)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        try {
            MethodSignature signature = (MethodSignature) point.getSignature();
            Method method = signature.getMethod();
            MultiDBS multiDBS = method.getAnnotation(MultiDBS.class);
            // 获取注解中指定的数据源标识
            if (multiDBS != null) {
                DataSourceContextHolder.setDataSourceKey(multiDBS.value());
            }
            logger.info("----------未配置多数据源，使用默认数据源------------");
            return point.proceed();
        } finally {
            DataSourceContextHolder.clearDataSourceKey();
        }
    }
}
